package com.xmg.p2p.base.controller;

import com.xmg.p2p.base.domain.UserFile;
import com.xmg.p2p.base.domain.Userinfo;
import com.xmg.p2p.base.query.UserFileQueryObject;
import com.xmg.p2p.base.service.AccountService;
import com.xmg.p2p.base.service.RealAuthService;
import com.xmg.p2p.base.service.UserFileService;
import com.xmg.p2p.base.service.UserinfoService;
import com.xmg.p2p.base.util.BidConst;
import com.xmg.p2p.base.util.JSONResult;
import com.xmg.p2p.base.util.UserContext;
import com.xmg.p2p.business.domain.BidRequest;
import com.xmg.p2p.business.service.IBidRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;

/**
 * @BelongsProject: jinrong-website
 * @BelongsPackage: com.xmg.p2p.base.controller
 * @author: Andy
 * @date: 2021.3.18 09:38
 * @Description: 我要借款控制器
 * @since JDK 1.8
 */
@Controller
public class BorrowController {

    @Autowired
    private AccountService accountService ;
    @Autowired
    private UserinfoService userinfoService;
    @Autowired
    private IBidRequestService bidRequestService;
    @Autowired
    private RealAuthService realAuthService;
    @Autowired
    private UserFileService userFileService;

    /**
     * 进入我的借款页面，展示用户的认证状态
     * @param model
     * @return
     */
    @RequestMapping("borrow")
    public String borrowIndex(Model model){
        if (UserContext.getCurrent() != null){
            // 因为是贷款，肯定会涉及到用户的账户信息，所以我们需要获取当前用户信息
            model.addAttribute("account",accountService.getById(UserContext.getCurrent().getId()));
            // 获取当前账户信息
            model.addAttribute("userinfo",userinfoService.getById(UserContext.getCurrent().getId()));
            // 获取最低风控的分数
            model.addAttribute("creditBorrowScore", BidConst.CREDIT_BORROW_SCORE);
            return "borrow";
        }else{
            return "redirect:main";
        }
    }


    /**
     * 跳转到申请借款的页面
     * @param model
     * @return
     */
    @RequestMapping("borrowInfo")
    public String borrowInfo(Model model) {
        // 获取当前用户信息
        Userinfo userinfo = this.userinfoService.getById(UserContext.getCurrent().getId());
        // 判断当前用户是否可以申请借款
        if (this.bidRequestService.canApply(userinfo)) {
            if (!userinfo.getHasBidRequestInProcess()) {//用户是否有借款在审核流程中,这也说明了用户提交申请之后咱们需要取修改userinfo里面的state
                //如果没有 添加属性到到model  跳转申请贷款页面
                model.addAttribute("account", this.accountService.getById(UserContext.getCurrent().getId()));//账户对象
                model.addAttribute("minBidRequestAmount",BidConst.SMALLEST_BIDREQUEST_AMOUNT);//最小借款金额
                model.addAttribute("minBidAmount",BidConst.SMALLEST_BID_AMOUNT);//最小投标金额
                return "borrow_apply" ;
            }else{
                //如果有 ,返回到 借款的等待审核页面
                return "borrow_apply_result" ;
            }
        }else{
            //否则 返回到borrow.do  申请借款首页
            return  "redirect:/borrow.do";
        }
    }

    /**
     * 申请借款的流程
     * @param bidRequest
     * @return
     */
    @RequestMapping("borrow_apply")
    public String borrowApply(BidRequest bidRequest){
        this.bidRequestService.apply(bidRequest);
        return "redirect:/borrowInfo.do";
    }


    /**
     * 查看借款的详细信息
     * @param id  要查询的借款信息的ID
     * @param model     模型
     * @return  返回是页面的名字
     */
    @RequestMapping("borrow_info")
    public String borrwInfoDetail(Long id,Model model){
        // 根据ID获取借款对象的信息
        BidRequest bidRequest = this.bidRequestService.getById(id);
        // 根据借款用户的ID获取用户信息
        Userinfo userinfo = this.userinfoService.getById(bidRequest.getCreateUser().getId());
        // 把查询出来的借款信息放到Model模型中
        model.addAttribute("bidRequest",bidRequest);
        // 把查询出来的用户信息放到Model模型中
        model.addAttribute("userInfo",userinfo);
        // 用户的实名认证信息
        model.addAttribute("realAuth",this.realAuthService.get(userinfo.getRealAuthId()));
        // 列出借款人的所有风控材料（审核通过）
        UserFileQueryObject qo = new UserFileQueryObject();
        qo.setState(UserFile.STATE_AUDIT);      // 设置状态为审核通过
        qo.setApplierId(userinfo.getId());
        qo.setPageSize(-1); // 表示不进行分页
        model.addAttribute("userFiles",this.userFileService.queryForList(qo));

        // 表示自己登陆的部分
        model.addAttribute("self",false);   // 表示没有登录的情况
        // 表示当前有用户登录
        if (UserContext.getCurrent() != null){
            // 判断当前用户是否是借款用户
            if (UserContext.getCurrent().getId() == bidRequest.getCreateUser().getId()){
                model.addAttribute("self",true);
            }else {
                model.addAttribute("account",this.accountService.getById(UserContext.getCurrent().getId()));
            }
        }
        return "borrow_info";
    }

    /**
     * 进行投标的操作
     * @param bidRequestId  借款对象的ID
     * @param amount    投标金额
     * @return
     */
    @ResponseBody
    @RequestMapping("borrow_bid")
    public JSONResult bid(Long bidRequestId, BigDecimal amount){
        JSONResult jsonResult = new JSONResult();
        try {
            this.bidRequestService.bid(bidRequestId,amount);
        }catch (Exception ex){
            ex.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMsg(ex.getMessage());
        }
        return jsonResult;
    }
}
